import { isArray, toBoolean } from '@jecloud/utils';
import { LayoutMenuType, MenuType } from '@/data/enum/menu';
import { LayoutType } from '@/data/enum/layout';
import Base from '../base';

/**
 * 菜单
 *
 * @export
 * @class SiderMenu
 */
export default class SiderMenu extends Base {
  /**
   * 子菜单
   *
   * @memberof Menu
   */
  children = [];
  /**
   * 菜单类型
   *
   * @memberof Menu
   */
  menuType = LayoutMenuType.SIDER;

  /**
   * 顶部菜单ids
   *
   */
  topMenus = [];

  constructor(options) {
    super();
    this.id = options.id;
    this.text = options.text;
    this.icon = options.icon || 'fal fa-circle';
    this.iconColor = options.iconColor;
    this.type = options.nodeInfoType;
    this.configInfo = options.nodeInfo;
    this.leaf = options.leaf;
    this.badge = 0; //Math.round(Math.random(0) * 100);
    this.path = options.nodePath;
    this.parent = options.parent;
    this.layout = options?.bean.MENU_LAYOUT ?? LayoutType.MAIN;
    this.code = this.configInfo?.split(',')[0]; // 菜单编码，特殊处理，去配置项的第一个配置
    this.loadFirstData = toBoolean(options?.bean.MENU_LOAD_FIRST_DATA); //加载第一条数据，配合表单功能使用
    this.options = {};
    switch (this.type) {
      case 'MT':
        this.type = MenuType.FUNC;
        this.options.view = options.bean?.MENU_FUNCTYPE;
        break;
      case 'IDDT':
        this.type = MenuType.PLUGIN;
        break;
    }
  }

  /**
   * 添加子节点
   *
   * @param {*} data
   * @return {*}
   * @memberof MenuModel
   */
  appendChild(data) {
    const children = isArray(data) ? data : [data];
    children.forEach((item) => {
      this.children.push(item.isModel ? item : new SiderMenu(item));
    });
  }

  /**
   * 级联子节点
   *
   * @param {*} fn
   * @return {*}
   * @memberof MenuModel
   */
  cascadeNodes(fn) {
    const flag = fn(this);
    if (flag === false) {
      return;
    }
    this.children?.forEach((item) => {
      item.cascadeNodes(fn);
    });
  }

  /**
   * 获取真实的功能菜单
   * @returns Array
   */
  getReallyMenus() {
    const menus = [];
    this.cascadeNodes((node) => {
      // 真实的功能菜单
      if (node.type !== 'MENU') {
        menus.push(node);
      }
    });
    return menus;
  }
}
